import React, { useState, useRef, useEffect } from 'react';
import {
  FileIcon,
  SaveIcon,
  FolderOpenIcon,
  DownloadIcon,
  MoonIcon,
  SunIcon,
  SplitSquareHorizontalIcon,
  EyeIcon,
  EditIcon
} from 'lucide-react';

interface ToolbarProps {
  onNewFile: () => void;
  onOpenFile: () => void;
  onSaveFile: () => void;
  onExport: (format: 'html' | 'pdf' | 'word') => void;
  onToggleTheme: () => void;
  onToggleView: (view: 'editor' | 'preview' | 'split') => void;
  onRenameFile: (newName: string) => void;
  isDark: boolean;
  currentView: 'editor' | 'preview' | 'split';
  fileName: string;
  isSaved: boolean;
}

export const Toolbar: React.FC<ToolbarProps> = ({
  onNewFile,
  onOpenFile,
  onSaveFile,
  onExport,
  onToggleTheme,
  onToggleView,
  onRenameFile,
  isDark,
  currentView,
  fileName,
  isSaved,
}) => {
  const [isEditing, setIsEditing] = useState(false);
  const [editName, setEditName] = useState(fileName);
  const inputRef = useRef<HTMLInputElement>(null);

  // 当fileName改变时更新editName
  useEffect(() => {
    setEditName(fileName);
  }, [fileName]);

  // 当进入编辑模式时聚焦输入框
  useEffect(() => {
    if (isEditing && inputRef.current) {
      inputRef.current.focus();
      inputRef.current.select();
    }
  }, [isEditing]);

  const handleDoubleClick = () => {
    setIsEditing(true);
  };

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter') {
      handleSubmit();
    } else if (e.key === 'Escape') {
      handleCancel();
    }
  };

  const handleSubmit = () => {
    const trimmedName = editName.trim();
    if (trimmedName && trimmedName !== fileName) {
      // 确保文件名以.md结尾
      const newName = trimmedName.endsWith('.md') ? trimmedName : `${trimmedName}.md`;
      onRenameFile(newName);
    }
    setIsEditing(false);
  };

  const handleCancel = () => {
    setEditName(fileName);
    setIsEditing(false);
  };

  const handleBlur = () => {
    handleSubmit();
  };
  return (
    <div className="flex items-center justify-between p-3 bg-gray-100 dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700">
      {/* 左侧文件操作 */}
      <div className="flex items-center space-x-2">
        <button
          onClick={onNewFile}
          className="p-2 hover:bg-gray-200 dark:hover:bg-gray-700 rounded-lg transition-colors"
          title="新建文件 (⌘N)"
        >
          <FileIcon size={18} className="text-gray-600 dark:text-gray-300" />
        </button>

        <button
          onClick={onOpenFile}
          className="p-2 hover:bg-gray-200 dark:hover:bg-gray-700 rounded-lg transition-colors"
          title="打开文件 (⌘O)"
        >
          <FolderOpenIcon size={18} className="text-gray-600 dark:text-gray-300" />
        </button>

        <button
          onClick={onSaveFile}
          className="p-2 hover:bg-gray-200 dark:hover:bg-gray-700 rounded-lg transition-colors"
          title="保存文件 (⌘S)"
        >
          <SaveIcon size={18} className={`${isSaved ? 'text-gray-600 dark:text-gray-300' : 'text-blue-600 dark:text-blue-400'}`} />
        </button>

        <div className="w-px h-6 bg-gray-300 dark:bg-gray-600 mx-2" />

        {/* 导出按钮 */}
        <div className="relative group">
          <button
            className="p-2 hover:bg-gray-200 dark:hover:bg-gray-700 rounded-lg transition-colors"
            title="导出"
          >
            <DownloadIcon size={18} className="text-gray-600 dark:text-gray-300" />
          </button>
          <div className="absolute top-full left-0 mt-1 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all z-10 whitespace-nowrap">
            <button
              onClick={() => onExport('html')}
              className="block w-full px-4 py-2 text-sm text-left hover:bg-gray-100 dark:hover:bg-gray-700 text-gray-700 dark:text-gray-300 whitespace-nowrap"
            >
              导出为 HTML
            </button>
            <button
              onClick={() => onExport('pdf')}
              className="block w-full px-4 py-2 text-sm text-left hover:bg-gray-100 dark:hover:bg-gray-700 text-gray-700 dark:text-gray-300 whitespace-nowrap"
            >
              导出为 PDF
            </button>
            <button
              onClick={() => onExport('word')}
              className="block w-full px-4 py-2 text-sm text-left hover:bg-gray-100 dark:hover:bg-gray-700 text-gray-700 dark:text-gray-300 whitespace-nowrap"
            >
              导出为 Word
            </button>
            <hr className="border-gray-200 dark:border-gray-600 my-1" />
            <button
              onClick={() => onExport('print')}
              className="block w-full px-4 py-2 text-sm text-left hover:bg-gray-100 dark:hover:bg-gray-700 text-gray-700 dark:text-gray-300 whitespace-nowrap"
            >
              🖶️ 打印预览
            </button>
          </div>
        </div>
      </div>

      {/* 中间文件名 */}
      <div className="flex items-center space-x-2">
        {isEditing ? (
          <input
            ref={inputRef}
            type="text"
            value={editName}
            onChange={(e) => setEditName(e.target.value)}
            onKeyDown={handleKeyDown}
            onBlur={handleBlur}
            className="text-sm font-medium bg-white dark:bg-gray-700 text-gray-700 dark:text-gray-300 border border-gray-300 dark:border-gray-600 rounded px-2 py-1 focus:outline-none focus:ring-2 focus:ring-blue-500"
            placeholder="输入文件名..."
          />
        ) : (
          <span
            className="text-sm font-medium text-gray-700 dark:text-gray-300 cursor-pointer hover:bg-gray-200 dark:hover:bg-gray-700 px-2 py-1 rounded transition-colors"
            onDoubleClick={handleDoubleClick}
            title="双击编辑文件名"
          >
            {fileName}
            {!isSaved && <span className="ml-1 text-orange-500">●</span>}
          </span>
        )}
      </div>

      {/* 右侧视图和主题控制 */}
      <div className="flex items-center space-x-2">
        {/* 视图切换 */}
        <div className="flex items-center bg-gray-200 dark:bg-gray-700 rounded-lg p-1">
          <button
            onClick={() => onToggleView('editor')}
            className={`p-1.5 rounded transition-colors ${
              currentView === 'editor'
                ? 'bg-white dark:bg-gray-600 shadow-sm'
                : 'hover:bg-gray-300 dark:hover:bg-gray-600'
            }`}
            title="仅编辑器"
          >
            <EditIcon size={16} className="text-gray-600 dark:text-gray-300" />
          </button>

          <button
            onClick={() => onToggleView('split')}
            className={`p-1.5 rounded transition-colors ${
              currentView === 'split'
                ? 'bg-white dark:bg-gray-600 shadow-sm'
                : 'hover:bg-gray-300 dark:hover:bg-gray-600'
            }`}
            title="分屏模式"
          >
            <SplitSquareHorizontalIcon size={16} className="text-gray-600 dark:text-gray-300" />
          </button>

          <button
            onClick={() => onToggleView('preview')}
            className={`p-1.5 rounded transition-colors ${
              currentView === 'preview'
                ? 'bg-white dark:bg-gray-600 shadow-sm'
                : 'hover:bg-gray-300 dark:hover:bg-gray-600'
            }`}
            title="仅预览"
          >
            <EyeIcon size={16} className="text-gray-600 dark:text-gray-300" />
          </button>
        </div>

        <div className="w-px h-6 bg-gray-300 dark:bg-gray-600 mx-2" />

        {/* 主题切换 */}
        <button
          onClick={onToggleTheme}
          className="p-2 hover:bg-gray-200 dark:hover:bg-gray-700 rounded-lg transition-colors"
          title={isDark ? '切换到亮色主题' : '切换到暗色主题'}
        >
          {isDark ? (
            <SunIcon size={18} className="text-yellow-500" />
          ) : (
            <MoonIcon size={18} className="text-gray-600" />
          )}
        </button>
      </div>
    </div>
  );
};

export default Toolbar;
